const { createCode } = require("@/utils/createCode");
const { ErrorCode } = require("@/utils/r/code");
const transport = require("@/utils/email");
const EmailModel = require("@/model/Email");
const z_base = require("@/dao/z_base");

const code = {
  async CreateCode(email) {
    /* 
        生成一个六位验证码，校验时期是三分钟,插入数据库的时间开始起计时
        邮箱和code保存数据库，用于注册校验是否正确
        将code发送给用户邮箱
    */
    const code = createCode();
    //每次创建新的验证码，都先查看是否存在该邮箱
    const existByEmail = await z_base.GetOne(EmailModel.EmailCode, { email });
    if (existByEmail && existByEmail.id) {
      await z_base.Update(
        EmailModel.EmailCode,
        {
          created_at: new Date().toLocaleString(), //更新起始时间
          code,
        },
        { id: existByEmail.id }
      );
    } else {
      //将数据保存到数据库
      await z_base.Create(EmailModel.EmailCode, { code, email });
    }

    //发送邮件
    const mailOption = {
      from: "2639776795@qq.com",
      to: email,
      subject: "验证码", //标题
      html: `<h1>${code}</h1>`,
    };
    // await transport.sendMail(mailOption, (err, res) => {
    //   if (err) {
    //     console.log(err);
    //     return "发送失败";
    //   } else {
    //     console.log("邮箱验证码发送成功");
    //   }
    //   transport.close();
    // });
    return ErrorCode.OK;
  },
};

module.exports = code;
